package room_event

import (
	"errors"
	"github.com/go-redis/redis"
	"github.com/spf13/cast"
	"longmen/server/config/global"
	cache3 "longmen/server/internal/rpc/tencentim/cache"
	"longmen/server/internal/rpc/tencentim/chat"
	imsdk2 "longmen/server/internal/rpc/tencentim/imsdk"
	messages2 "longmen/server/internal/rpc/tencentim/messages"
	"longmen/server/internal/rpc/tencentim/pvt_chat"
	"longmen/server/internal/rpc/tencentim/utils"
	"longmen/server/internal/services/consumers/publisher"
	utils2 "longmen/server/internal/services/nami/utils"
	"longmen/server/pkg/db/mysql/models/models_main"
	"longmen/server/pkg/db/redis/cache"
	pb "longmen/server/pkg/protobuf"
	"time"
)

func handlingFirst(req *pb.CallbackReq, usr *chat.ClientUser) (ret *pb.CallbackResp, err error) {
	defer func() {
		//crontab.ReplayChatClientHub.EnterReplayRoom(usr.RoomId, usr.UserId)
	}()

	rep := &messages2.LoginReplyMessage{}

	//global.Log.Debugf("IncrIpStats handlingLogin 渠道ID:%+v", usr.SourceKey)

	rep.Type = messages2.LoginReplyMessageType
	rep.Message = "loginRep"
	rep.User = &messages2.LoginReplyMessageUserInfo{
		Platform:   usr.Platform,
		UserId:     usr.UserId,
		RoomId:     usr.RoomId,
		ClientName: usr.ClientName,
		Avatar:     usr.Avatar,
		Level:      usr.Level,
		Vip:        usr.Vip,
		Role:       usr.Role,
		Permit:     usr.Permit,
		Anonymouse: usr.Anonymouse,
	}

	rep.Data = &messages2.LoginReplyMessageData{}
	rep.Data.Guess = cache.GetLastGuessStatusMsgForRoom(usr.RoomId)
	rep.Data.ChatHistory = GetChatHistory(usr.RoomId).GetChatHistory()
	// 填充在线用户列表``
	count := 0

	configPub := cache.GetConfigPub()
	rep.Data.Message = configPub.ChatSysMessage

	rep.Data.OnlineNum = count
	//if !cache.RepeatedIPJoin(usr.RoomId, usr.IP) {
	cache3.PushLoginInfo(usr, true)
	//} else {
	//global.Log.Infof("repeated IP:%s", usr.IP)
	//}
	anchor, err := cache.GetUserFullInfo(usr.RoomId)
	if err == nil && anchor.Id > 0 {
		cache3.SetEntryExitTimes(usr, "login")
		pvt_chat.NewOnlineDevice().WriteToRedis(pvt_chat.OnlineDeviceRequest{
			DeviceId:       cast.ToString(usr.UserId),
			Platform:       usr.Platform,
			UserID:         cast.ToString(usr.UserId),
			Nickname:       usr.ClientName,
			UserLevel:      usr.Level,
			RoomID:         usr.RoomId,
			LastOnlineTime: time.Now().Unix(),
		})
		conversation, err := pvt_chat.GetSingleChatConversationSendIdToRecvId(cast.ToString(usr.RoomId), cast.ToString(usr.UserId))
		if err == nil && conversation != nil {
			//cache3.RoomUserOnline(usr.RoomId, usr.UserId) // 更新 cache - 加入 房间
		}
	}

	// 渠道统计
	if len(usr.SourceKey) > 0 {
		err = global.PublishChannelStats.Send(publisher.ActiveChannelStats, models_main.User{Id: usr.UserId, RegSourceId: usr.SourceKey})
		if err != nil {
			global.Log.Errorf("Nats publish chanel %s", err.Error())
		}
	}

	IncrIpStats(usr.RoomId, usr.IP)
	//cache3.IncGlobalLiveRoomIp(usr.IP) 改到livePageData接口统计

	utils2.SafeGo(func() {
		setTimUserNick(req.From_Account, usr.ClientName)
	})
	return utils.CallbackOkAndExt(rep, cast.ToString(usr.RoomId)), nil
}

func setTimUserNick(fromAccount, nick string) {
	if len(nick) <= 0 || len(fromAccount) <= 0 {
		return
	}
	key := "tim_nickname_from_account:" + fromAccount
	rds := global.GetRds()
	nickname, err := rds.Get(key).Result()
	if err != nil && !errors.Is(err, redis.Nil) {
		global.Log.Errorf("rds.Exists error:%+v", err)
		return
	}
	if len(nickname) <= 0 || nickname != nick {
		tag := "Tag_Profile_IM_Nick"
		ok, res := imsdk2.GetSdk().PortraitGetRequest(imsdk2.ProfilePortraitGetRequest{
			ToAccount: []string{fromAccount},
			TagList:   []string{tag},
		})
		if !ok {
			return
		}
		needUpdate := false
		for _, v := range res.UserProfileItem {
			if v.ResultCode == 0 && v.ToAccount == fromAccount {
				if len(v.ProfileItem) <= 0 {
					needUpdate = true
					break
				}
				for _, profileTag := range v.ProfileItem {
					if profileTag.Tag == tag {
						//tim资料昵称如果没有改变设置缓存, 如果变化就更新
						if profileTag.Value != nick {
							needUpdate = true
						} else {
							rds.Set(key, nick, time.Minute)
							return
						}
					}
				}
			}
		}

		if !needUpdate {
			return
		}
		ok, res2 := imsdk2.GetSdk().PortraitSetRequest(imsdk2.ProfilePortraitSetRequest{
			FromAccount: fromAccount,
			ProfileItem: []imsdk2.ProfilePortraitSetTag{
				{
					Tag:   tag,
					Value: nick,
				},
			},
		})
		if !ok {
			global.Log.Errorf("setUserNick error:%+v", res2)
			return
		}
		rds.Set(key, nick, time.Minute)
	}
}
